package com.example.widget_lib.scroller;

import com.example.widget_lib.callback.ScrollMoveListener;
import com.example.widget_lib.utils.LogUtil;
import ohos.agp.components.ScrollHelper;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

public class AutoScroller implements Runnable {

    private final ScrollHelper mScroller;
    private int mLastX;
    private int mLastY;
    private boolean mIsFinish;

    private EventHandler mEventHandler;
    private ScrollMoveListener listener;

    public AutoScroller() {
        mScroller = new ScrollHelper();
        mEventHandler = new EventHandler(EventRunner.getMainEventRunner());
        mIsFinish = true;
    }

    public void setListener(ScrollMoveListener listener) {
        this.listener = listener;
    }

    @Override
    public void run() {
        LogUtil.loge("=== run");
        if (!mScroller.isFinished()) {
            mScroller.updateScroll();
            if (listener != null) {
                LogUtil.loge("mLastX: " + mLastX + "= AXIS_X: " + mScroller.getCurrValue(ScrollHelper.AXIS_X) + "" + " AXIS_Y: " + mScroller.getCurrValue(ScrollHelper.AXIS_Y));
                listener.fling(mLastX - mScroller.getCurrValue(ScrollHelper.AXIS_X), mLastY - mScroller.getCurrValue(ScrollHelper.AXIS_Y));
            }
            mLastX = mScroller.getCurrValue(ScrollHelper.AXIS_X);
            mLastY = mScroller.getCurrValue(ScrollHelper.AXIS_Y);
            mEventHandler.postTask(this, 10);
        } else {
            mEventHandler.removeTask(this);
            mIsFinish = true;
        }
    }

    public void start(int disX, int disY) {
        mEventHandler.removeTask(this);
        mLastX = 0;
        mLastY = 0;
        mIsFinish = false;
        mScroller.startScroll(0, 0, disX, disY);
        mEventHandler.postTask(this);
    }

    public boolean isFinish() {
        return mIsFinish;
    }
}